package com.jfs.strategy.register.impl;

import cn.hutool.core.util.StrUtil;
import com.jfs.envent.EventPublisher;
import com.jfs.envent.entity.DeviceOnlineEventEntity;
import com.jfs.observer.request.abstracts.AbstractProcessor;
import com.jfs.strategy.register.RegisterStrategy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sip.RequestEvent;

/**
 * @Description 设备注册策略
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
@Component
@Slf4j
@AllArgsConstructor
public class RegisterStrategyImpl implements RegisterStrategy {
    private final EventPublisher eventPublisher;

    @Override
    public boolean support(RequestEvent requestEvent) {
        return requestEvent.getRequest().getExpires().getExpires() > 0;
    }

    @Override
    public void processor(AbstractProcessor abstractProcessor, RequestEvent requestEvent) {
        //执行登录逻辑
        try {
            if (StrUtil.isEmpty(abstractProcessor.getSipPassword()) || abstractProcessor.isAuthorizationPass(requestEvent, abstractProcessor.getSipPassword())) {
                abstractProcessor.doSuccess(requestEvent);
                if (log.isDebugEnabled()) {
                    log.debug("【设备号：{}】,注册响应200", abstractProcessor.getDeviceIdFromRequest(requestEvent));
                }
                //发布设备上线事件
                DeviceOnlineEventEntity deviceOnlineEventEntity = new DeviceOnlineEventEntity(this);
                deviceOnlineEventEntity.setDeviceID(abstractProcessor.getDeviceIdFromRequest(requestEvent));
                deviceOnlineEventEntity.setRequestEvent(requestEvent);
                deviceOnlineEventEntity.setIp(abstractProcessor.getIpByRequest(requestEvent));
                deviceOnlineEventEntity.setPort(abstractProcessor.getPortFromRequest(requestEvent));
                deviceOnlineEventEntity.setTransport(abstractProcessor.getTransactionFormRequest(requestEvent));
                eventPublisher.publish(deviceOnlineEventEntity);
            } else if (abstractProcessor.isAuth(requestEvent)) {
                //响应 401
                abstractProcessor.doUnAuthorized401(requestEvent);
                if (log.isDebugEnabled()) {
                    log.debug("【设备号：{}】,注册响应401", abstractProcessor.getDeviceIdFromRequest(requestEvent));
                }
            } else {
                //403 未授权
                abstractProcessor.doLoginFail403(requestEvent);
                log.error("【设备号：{}】,注册失败响应403", abstractProcessor.getDeviceIdFromRequest(requestEvent));
            }
        } catch (Exception e) {
            log.error("设备注册发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
